﻿using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
#if UNITY_EDITOR
#endif

namespace JH
{
    public static class StopAndResetContent
    {
        /// <summary>
        /// 立即停止滚动并重置内容到初始位置
        /// </summary>
        public static void StopAndResetContentEm(this ScrollRect scrollRect)
        {
            // 参数检查
            if (scrollRect == null) throw new ArgumentNullException(nameof(scrollRect));

            // 停止所有滚动动作
            scrollRect.velocity = Vector2.zero;
            scrollRect.StopMovement();

            // 使用 normalizedPosition 重置位置
            Vector2 normalizedPosition = scrollRect.normalizedPosition;

            //根据滚动方向重置位置
            if (scrollRect.vertical) normalizedPosition.y = 1;
            if (scrollRect.horizontal) normalizedPosition.x = 0;

            // 重置位置
            scrollRect.normalizedPosition = normalizedPosition;
        }

#if UNITY_EDITOR
        /// <summary>
        ///  编辑器下，测试立即停止滚动并重置内容到初始位置
        /// </summary>
        [MenuItem("CONTEXT/ScrollRect/Test Stop And Reset Content")]
        public static void TestStopAndResetContent(MenuCommand command)
        {
            ScrollRect scrollRect = command.context as ScrollRect;
            if (scrollRect != null)
            {
                Undo.RecordObject(scrollRect.content, "Test Stop And Reset Content");
                scrollRect.StopAndResetContentEm();
                EditorUtility.SetDirty(scrollRect.content);
                Debug.Log("成功停止滚动并重置内容到初始位置");
            }
            else
            {
                Debug.LogError("无法获取ScrollRect组件!");
            }
        }
#endif
    }
}